import fileinput, re
import numpy, scipy.stats

from retraction_unfolding_filter import RetractionCurve, RetractionSegment, RetractionPeak

element_pattern = re.compile(
    r'<element notes="\[(?P<notes>[^"]*)\]" path="(?P<path>[^"]+)"/>')

def nice_stats(values):
    if values:
        sorted_values = sorted(values)
        # Bessel's correction
        return "Average=%s Median=%s PopulationStd=%s Count=%s" % (
            numpy.average(values), numpy.median(values),
            numpy.std(values) * numpy.sqrt(len(values) / (len(values) - 1.0)),
            len(values))
    else:
        return "No values."

def gumbel_l_loc_scale(forces):
    # Left-skewed Gumbel.
    xopt = scipy.optimize.fmin(
        lambda x: -numpy.log(
            scipy.stats.gumbel_l(loc=x[0], scale=x[1]).pdf(
                forces)).sum(), x0=[
            numpy.mean(forces), numpy.std(forces)])
    return xopt

def extract_path_data(line):
    path, data = None, []
    m = element_pattern.match(line)
    if m:
        path = m.group("path")
        notes_group = m.group("notes")
        if notes_group:
	    assert notes_group[0] == "(" and notes_group[-1] == ")"
	    clfs = notes_group[1:-1].split("), (")
	    for clf in clfs:
		if clf:
		    a = clf.split(", ")
                    assert len(a) in (2, 4)
                    data.append(
                        (float(a[0]), float(a[1]),
                        0 if len(a) == 2 else float(a[2]),
                        0 if len(a) == 2 else float(a[3])))
    elif line.startswith("RetractionCurve("):
        retraction_curve = eval(line)
        path = retraction_curve.path
        cl_f_z_d_list = retraction_curve.contour_length_rupture_force_extension_and_distance_of_peaks() if len(retraction_curve) else []
        data = [
            (a[0] * 1e9, a[1] * 1e12, a[2] * 1e9, a[3] * 1e9) for a in cl_f_z_d_list]
    return path, data

def extract_data(line):
    return extract_path_data(line)[1]

def main():
    values = []
    for line in fileinput.input():
	line = line.strip()
	if line:
	    values.append(float(line))
    print(nice_stats(values))


if __name__ == "__main__":
    main()
